package com.songlanyun.common.utils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Csv导入导出工具
 **/
public class CsvUtils {
    HttpServletResponse response;
    HttpServletRequest request;
    // 文件名
    private String fileName;


    public static CsvUtils getInstance(HttpServletRequest request,HttpServletResponse response, String fileName) {
        CsvUtils eu=new CsvUtils();
        eu.response = response;
        eu.request=request;
        eu.fileName=fileName;
        return eu;
    }


    public void writeCSV(String titleColumn[], String headers[], int titleSize[], List<?> dataList){
        try {
            //写入临时文件
            File tempFile = File.createTempFile("vehicle", ".csv");
            CsvWriter csvWriter = new CsvWriter(tempFile.getCanonicalPath(),',', Charset.forName("UTF-8"));
            // 写表头
            csvWriter.writeRecord(headers);
            if (dataList != null && dataList.size() > 0&&titleColumn.length > 0) {
                for (int rowIndex = 1; rowIndex <= dataList.size(); rowIndex++) {
                    Object obj = dataList.get(rowIndex - 1); // 获得该对象
                    Class clsss = obj.getClass(); // 获得该对对象的class实例
                    //Row dataRow = workbook.getSheet(sheetName).createRow(rowIndex);
                    for (int columnIndex = 0; columnIndex < titleColumn.length; columnIndex++) {
                        String title = titleColumn[columnIndex].trim();
                        if (!"".equals(title)) { // 字段不为空
                            // 使首字母大写
                            String UTitle = Character.toUpperCase(title.charAt(0))
                                    + title.substring(1, title.length()); // 使其首字母大写;
                            String methodName = "get" + UTitle;

                            // 设置要执行的方法
                            Method method = clsss.getDeclaredMethod(methodName);

                            // 获取返回类型
                            String returnType = method.getReturnType().getName();

                            Object data = method.invoke(obj) == null ? "" : method.invoke(obj);
                            String str ="";
                            if (data != null && !"".equals(data)) {
                                if ("int".equals(returnType)||"long".equals(returnType)||"float".equals(returnType)||"double".equals(returnType)) {
                                    str = data+"";
                                }else if ("java.util.Date".equals(returnType)) {
                                    SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    try{
                                        str = sdf.format((Date)data);
                                    }catch (Exception e){}
                                } else {
                                    str = data.toString();
                                }
                            }
                            csvWriter.write(str+"\t");
                        }
                    }
                    csvWriter.endRecord();
                }

            }
            csvWriter.close();
            /**
             * 写入csv结束，写出流
             */
            java.io.OutputStream out = response.getOutputStream();
            byte[] b = new byte[10240];
            java.io.File fileLoad = new java.io.File(tempFile.getCanonicalPath());
            response.reset();
            response.setContentType("application/csv");
            response.setHeader("content-disposition", "attachment; filename="+fileName+".csv");
            response.setHeader("content-type", "text/csv;charset=UTF-8");
            long fileLength = fileLoad.length();
            String length1 = String.valueOf(fileLength);
            response.setHeader("Content_Length", length1);
            java.io.FileInputStream in = new java.io.FileInputStream(fileLoad);
            int n;
            out.write(new   byte []{( byte ) 0xEF ,( byte ) 0xBB ,( byte ) 0xBF });
            while ((n = in.read(b)) != -1) {
                out.write(b, 0, n); //每次写入out1024字节
            }
            in.close();
            out.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void writeCsvWithStream(String titleColumn[], String headers[], int titleSize[], List<?> dataList){
        try {
            //写入临时文件
            File tempFile = File.createTempFile("vehicle", ".csv");
            CsvWriter csvWriter = new CsvWriter(tempFile.getCanonicalPath(),',', Charset.forName("UTF-8"));
            // 写表头
            csvWriter.writeRecord(headers);
            if (dataList != null && dataList.size() > 0&&titleColumn.length > 0) {
                for (int rowIndex = 1; rowIndex <= dataList.size(); rowIndex++) {
                    Object obj = dataList.get(rowIndex - 1); // 获得该对象
                    Class clsss = obj.getClass(); // 获得该对对象的class实例
                    //Row dataRow = workbook.getSheet(sheetName).createRow(rowIndex);
                    for (int columnIndex = 0; columnIndex < titleColumn.length; columnIndex++) {
                        String title = titleColumn[columnIndex].trim();
                        if (!"".equals(title)) { // 字段不为空
                            // 使首字母大写
                            String UTitle = Character.toUpperCase(title.charAt(0))
                                    + title.substring(1, title.length()); // 使其首字母大写;
                            String methodName = "get" + UTitle;

                            // 设置要执行的方法
                            Method method = clsss.getDeclaredMethod(methodName);

                            // 获取返回类型
                            String returnType = method.getReturnType().getName();

                            Object data = method.invoke(obj) == null ? "" : method.invoke(obj);
                            String str ="";
                            if (data != null && !"".equals(data)) {
                                if ("int".equals(returnType)||"long".equals(returnType)||"float".equals(returnType)||"double".equals(returnType)) {
                                    str = data+"";
                                }else if ("java.util.Date".equals(returnType)) {
                                    SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    try{
                                        str = sdf.format((Date)data);
                                    }catch (Exception e){}
                                } else {
                                    str = data.toString();
                                }
                            }
                            csvWriter.write(str+"\t");
                        }
                    }
                    csvWriter.endRecord();
                }

            }
            csvWriter.close();
            /**
             * 写入csv结束，写出流
             */
            FileInputStream fis = new FileInputStream(tempFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1)
            {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();

            byte[] content = bos.toByteArray();
            InputStream is = new ByteArrayInputStream(content);
            // 设置response参数，可以打开下载页面
            response.reset();
            response.setContentType("application/vnd.ms-excel;charset=utf-8");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
            ServletOutputStream out = response.getOutputStream();
            BufferedInputStream bis = null;
            BufferedOutputStream bufferedOutputStream = null;
            try {
                bis = new BufferedInputStream(is);
                bufferedOutputStream = new BufferedOutputStream(out);
                byte[] buff = new byte[2048];
                int bytesRead;
                // Simple read/write loop.
                while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                    bufferedOutputStream.write(buff, 0, bytesRead);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null)
                    bufferedOutputStream.close();
                if (bufferedOutputStream != null)
                    bufferedOutputStream.close();
            }
            out.flush();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public ByteArrayOutputStream getOutputStream(String titleColumn[], String headers[], int titleSize[], List<?> dataList){
        ByteArrayOutputStream bos = null;
        try {
            //写入临时文件
            File tempFile = File.createTempFile("vehicle", ".csv");
            CsvWriter csvWriter = new CsvWriter(tempFile.getCanonicalPath(),',', Charset.forName("UTF-8"));
            // 写表头
            csvWriter.writeRecord(headers);
            if (dataList != null && dataList.size() > 0&&titleColumn.length > 0) {
                for (int rowIndex = 1; rowIndex <= dataList.size(); rowIndex++) {
                    Object obj = dataList.get(rowIndex - 1); // 获得该对象
                    Class clsss = obj.getClass(); // 获得该对对象的class实例
                    //Row dataRow = workbook.getSheet(sheetName).createRow(rowIndex);
                    for (int columnIndex = 0; columnIndex < titleColumn.length; columnIndex++) {
                        String title = titleColumn[columnIndex].trim();
                        if (!"".equals(title)) { // 字段不为空
                            // 使首字母大写
                            String UTitle = Character.toUpperCase(title.charAt(0))
                                    + title.substring(1, title.length()); // 使其首字母大写;
                            String methodName = "get" + UTitle;

                            // 设置要执行的方法
                            Method method = clsss.getDeclaredMethod(methodName);

                            // 获取返回类型
                            String returnType = method.getReturnType().getName();

                            Object data = method.invoke(obj) == null ? "" : method.invoke(obj);
                            String str ="";
                            if (data != null && !"".equals(data)) {
                                if ("int".equals(returnType)||"long".equals(returnType)||"float".equals(returnType)||"double".equals(returnType)) {
                                    str = data+"";
                                }else if ("java.util.Date".equals(returnType)) {
                                    SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    try{
                                        str = sdf.format((Date)data);
                                    }catch (Exception e){}
                                } else {
                                    str = data.toString();
                                }
                            }
                            csvWriter.write(str+"\t");
                        }
                    }
                    csvWriter.endRecord();
                }

            }
            csvWriter.close();
            /**
             * 写入csv结束，写出流
             */
            FileInputStream fis = new FileInputStream(tempFile);
            bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1)
            {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();


        } catch (Exception e) {
            e.printStackTrace();
        }
        return bos;
    }

}


//public class CSVUtils {
//    private static final char DEFAULT_SEPARATOR = ',';
//
//    public static void writeLine(Writer w, List<String> values) throws IOException {
//        writeLine(w, values, DEFAULT_SEPARATOR, ' ');
//    }
//
//    public static void writeLine(Writer w, List<String> values, char separators) throws IOException {
//        writeLine(w, values, separators, ' ');
//    }
//
//    //https://tools.ietf.org/html/rfc4180
//    private static String followCVSformat(String value) {
//
//        String result = value;
//        if (result.contains("\"")) {
//            result = result.replace("\"", "\"\"");
//        }
//        return result;
//
//    }
//
//    public static void writeLine(Writer w, List<String> values, char separators, char customQuote) throws IOException {
//
//        boolean first = true;
//
//        //default customQuote is empty
//
//        if (separators == ' ') {
//            separators = DEFAULT_SEPARATOR;
//        }
//
//        StringBuilder sb = new StringBuilder();
//        for (String value : values) {
//            if (!first) {
//                sb.append(separators);
//            }
//            if (customQuote == ' ') {
//                sb.append(followCVSformat(value));
//            } else {
//                sb.append(customQuote).append(followCVSformat(value)).append(customQuote);
//            }
//
//            first = false;
//        }
//        sb.append("\n");
//        w.append(sb.toString());
//
//
//    }
//
//}
